﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Web;
using System.Net;

namespace Electure.DAL
{
    public class Attachment : BaseModel
    {
        public string OriginalName { get; set; }
        public string FileName { get; set; }
        public string FilePath { get;   set;}
        public string ContentType { get; set; }
        public long ContentLength { get; set; }
        public bool IsDirty { get; set; }

        public string GetFullPath()
        {
            return (FilePath == "/"
                    ? "~/" + "Content/Images" + FilePath
                    : ConfigurationManager.AppSettings["VideoStorePath"] + FilePath)
                    + FileName;
        }

        public string FullPath
        {
            get
            {
                return (FilePath == "/"
                    ? "~/" + "Content/Images" + FilePath
                    : ConfigurationManager.AppSettings["VideoStorePath"] + FilePath)
                    + FileName;
            }
        }

    }

    public class AttachmentRepository: BaseRepository<Attachment>
    {
        internal AttachmentRepository() { }

        public int CreateVideoAttachment(string originalFileName, string fileType, Stream fileStream)
        {            
            string storePath = ConfigurationManager.AppSettings["FtpStorePath"],
                filePath = ConfigurationManager.AppSettings["PathForSaveVideo"],
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(originalFileName);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(storePath + filePath + fileName);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;
            request.KeepAlive = true;
            request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ftp_login"], ConfigurationManager.AppSettings["ftp_pass"]);
            byte[] buffer = new byte[4097];
            int bytes = 0;
            int total_bytes = (int)fileStream.Length;
            Stream requestStream = request.GetRequestStream();
            while (total_bytes > 0)
            {
                bytes = fileStream.Read(buffer, 0, buffer.Length);
                requestStream.Write(buffer, 0, bytes);
                total_bytes = total_bytes - bytes;
            }
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            int id = Create(new Attachment()
            {
                OriginalName = originalFileName,
                FilePath = filePath,
                ContentType = fileType,
                FileName = fileName.ToLower(),
                ContentLength = fileStream.Length,
                IsDirty = true
            });

            return id;
        }
        public int CreateImageAttachment(string applicationPath, string originalFileName, string fileType, Stream fileStream)
        {
            string storePath = "Content/Images",
                filePath = "/",
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(originalFileName);

            using (var file = File.Create(applicationPath + storePath + filePath + fileName))
            {
                fileStream.CopyTo(file);
            }

            return Create(new Attachment()
            {
                OriginalName = originalFileName,
                FilePath = filePath,
                ContentType = fileType,
                FileName = fileName.ToLower(),
                ContentLength = fileStream.Length,
                IsDirty = false
            });
        }
        protected override int create(Attachment instance)
        {
            return connection.Execute(@"INSERT INTO attachment (OriginalName,FileName,FilePath,ContentType,ContentLength,IsDirty)
                            values(@OriginalName,@FileName,@FilePath,@ContentType,@ContentLength,@IsDirty)", instance);
        }
        public override List<Attachment> GetAll()
        {
            throw new NotImplementedException();
        }
        public override bool Delete(int id)
        {
            throw new NotImplementedException();
        }
        public override bool Update(Attachment instance)
        {
            return connection.Execute(@"UPDATE attachment SET OriginalName = @OriginalName, FileName = @FileName, FilePath = @FilePath,
                        ContentType = @ContentType,ContentLength = @ContentLength, IsDirty = @IsDirty", instance) == 1;
        }
    }
}
